package com.zdd.ehe.Realm;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zdd.ehe.entity.User;
import com.zdd.ehe.service.IRoleService;
import com.zdd.ehe.service.IUserService;
import com.zdd.ehe.util.JwtUtil;
import com.zdd.ehe.vo.UserVo;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @title:AccountRealm
 * @author:ZhuiZhu
 * @description:自定义Realm
 * @createDate: 2023/3/14  15:45
 */
@Component
public class AccountRealm extends AuthorizingRealm {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private IUserService userService;
    @Resource
    private IRoleService roleService;

    /**
     * 告诉该realm，我们支持的是jwtToken,而不是其余token
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        //返回一个判断，判断该token是否是jwtToken。如果是则支持
        //return token instanceof JwtToken;
        return true;
    }

    /**
     * 授权(验证权限时调用)
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        UserVo user = (UserVo) principalCollection.getPrimaryPrincipal();
        // 获取用户角色列表
        /*List<String> roleList = userService.getRoles(user.getId());*/
        // 根据角色列表获取权限集合
       /* Set<String> permissionSet = new HashSet<>();
        for(int i=0;i<roleList.size();i++){
            List<String> permissionList = roleService.getPermissions(roleList.get(i));
            for(int j=0;j<permissionList.size();j++){
                permissionSet.add(permissionList.get(j));
            }
        }*/

        Set<String> permissionSet = new HashSet<>();
        Set<String> roleSet = new HashSet<>();

        String permissions = (String) redisTemplate.opsForValue().get(user.getId() + "_p");
        String roles = (String) redisTemplate.opsForValue().get(user.getId() + "_r");

        List<String> permissionList = JSONObject.parseArray(permissions,String.class);
        List<String> roleList = JSONObject.parseArray(roles,String.class);

        for(String permisiion:permissionList){
            permissionSet.add(permisiion);
        }
        for(String role:roleList){
            roleSet.add(role);
        }

        //用户权限列表
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permissionSet);
        info.setRoles(roleSet);
        return info;
    }

    /**
     * 通过token信息，获取account,从而获取真实认证信息
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String account = (String)authenticationToken.getPrincipal();
        User user = userService.getOne(new QueryWrapper<User>().eq("account", account));

        if (user == null){
            throw new UnknownAccountException("该账户未注册");
        }
        if (user.getDel().equals("-1")){
            throw new LockedAccountException("账户锁定");
        }

        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);

        return new SimpleAuthenticationInfo(userVo, user.getPassword() ,"AccountRealm");
    }



}
